<template>
  <div class="newOrder">
    <el-breadcrumb separator="/" class="drugRecommend-breadcrumb">
      <el-breadcrumb-item
      ><span style="font-size: 16px">订单管理</span></el-breadcrumb-item
      >
      <el-breadcrumb-item
      ><span style="font-size: 18px">最新订单</span></el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="center">
      <div class="filter">
        <el-button @click="lookAll">查看全部</el-button>
        <span class="addressFilter">地区筛选：</span
        ><el-cascader
          :options="options"
          :props="{ expandTrigger: 'hover' }"
          clearable
          v-model="areaArr"
          @change="chooseArea()"
      >
      </el-cascader>
        <el-button @click="selectWithAddress">筛选</el-button>
        <span class="search">精确搜索：</span>
        <el-input
            placeholder="请输入内容"
            v-model="input"
            class="input-with-select"
            clearable
        >
          <el-select v-model="select" slot="prepend" placeholder="请选择">
            <el-option label="订单编号" value="1"></el-option>
            <el-option label="客户名" value="2"></el-option>
            <el-option label="联系方式" value="3"></el-option>
          </el-select>
          <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchWithContent"
          ></el-button>
        </el-input>
      </div>
      <div class="table">
        <el-table :data="newOrders" v-loading="loading" style="width: 100%">
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下单时间" width="180">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 6px">{{ scope.row.gmtCreate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" width="190">
            <template slot-scope="scope">
              <span>{{ scope.row.orderId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户名" width="90">
            <template slot-scope="scope">
              <span>{{ scope.row.receiptName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.phone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所在地区" width="180">
            <template slot-scope="scope">
              <span>{{ showAddress(scope.row.receiptAddress) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="交易金额 (元)" width="110">
            <template slot-scope="scope">
              <span>￥{{ parseFloat(scope.row.payment).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="购买 (种)" width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.itemAmount }} </span>
            </template>
          </el-table-column>
          <el-table-column label="交易状态" width="90">
            <template slot-scope="scope">
              <el-tag :type="type" size="medium">{{
                  showStatus(scope.row.status)
                }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <OrderDetails :detailsInfo="scope.row" class="OrderDetails"
              >详细</OrderDetails
              >
              <el-button size="mini" type="primary" @click="sendDrug(scope.row)"
              >派单</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-drawer
        title="服务派单"
        :before-close="handleClose"
        :visible.sync="dialog"
        direction="ltr"
        custom-class="demo-drawer"
        ref="drawer"
        @open="initMap"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <el-form-item label="服务类型" :label-width="formLabelWidth">
            <el-select v-model="selectedService" placeholder="请选择服务类型">
              <el-option
                  v-for="service in services"
                  :key="service.value"
                  :label="service.label"
                  :value="service.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="服务人员" :label-width="formLabelWidth">
            <el-select v-model="form.emp" placeholder="请选择服务人员">
              <el-option
                  v-for="item in adminList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.realName"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="服务人员" :label-width="formLabelWidth">-->
          <!--            <el-input v-model="form.emp" autocomplete="off" placeholder="请输入服务人员"></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="联系方式" :label-width="formLabelWidth">
            <el-input v-model="form.empPhone" autocomplete="off" placeholder="请输入服务人员电话"></el-input>
          </el-form-item>
          <!--          <el-form-item label="家政公司" :label-width="formLabelWidth">-->
          <!--            <el-input v-model="form.empCompany" autocomplete="off" placeholder="请输入家政公司"></el-input>-->
          <!--          </el-form-item>-->
          <!-- <el-form-item label="活动区域" :label-width="formLabelWidth">
             <el-select v-model="form.region" placeholder="请选择活动区域">
               <el-option label="区域一" value="shanghai"></el-option>
               <el-option label="区域二" value="beijing"></el-option>
             </el-select>
           </el-form-item>-->
        </el-form>
        <div class="app-container">
          <!--      表单-->
          <div style="width: 90%;margin-left: 10%;">
            <!--<el-input :value="startCoordinateDescription" disabled style="; margin-bottom: 3px;">-->
            <el-button slot="prepend" style="width: 120px; background: #13ce66; color: white"
                       @click="isStart = true">请选择出发点</el-button>
            <!--</el-input>-->
            <!--<el-input :value="endCoordinateDescription" disabled>-->
            <el-button slot="prepend" style="width: 120px; background: #cc3333; color: white"
                       @click="isStart = false">请选择目的地</el-button>
            <!--</el-input>-->
            <el-button  style="width: 120px; background: #4554ff; color: white"
                        @click="shengchengluj">生成路径规划</el-button>
            <br>
            <br>
            <ul v-for="item in instructionArr" v-if="ulShow">
              <li>{{item}}</li>
            </ul>
          </div>
          <!--      地图组件-->
          <div id="guide-map" style="margin:0px auto;width:500px;height: 300px;"></div>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="sendOrder" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import OrderDetails from "@/admin/order/components/OrderDetails";
import AMapLoader from "@amap/amap-jsapi-loader";
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: 'c0855ec0cf8fa39893bd7d8898993f70',
}
export default {

  components: {
    OrderDetails,
  },
  mounted() {
  },
  data() {
    return {
      selectedService: '', // 用于绑定选中的值
      services: [],
      ulShow:false,
      instructionArr:[],//路径规划中文介绍
      polylineArr:[],//路径规划线路经纬度
      //提交表单
      form: {},
      //地图实例
      map: null,
      //路径坐标点集合
      coordinateList: [],
      //起点坐标
      startCoordinate: {},
      //终点坐标
      endCoordinate: {},
      //起点坐标描述
      startCoordinateDescription: '默认经纬度',
      //终点坐标描述
      endCoordinateDescription: '默认经纬度',
      //选择起点
      isStart: true,
      //起点Marker
      startMarker: null,
      //终点Marker
      endMarker: null,
      table: false,
      dialog: false,
      loading: false,
      form: {
        emp: '',//服务人员
        empPhone: '',//服务人员电话
        empCompany: '',//家政公司
        instruction:'',//路径规划提示
        polyline:'',//路径规划坐标
      },
      formLabelWidth: '80px',
      timer: null,
      flag: 0,
      // 搜索的内容
      input: "",
      // 搜索的前缀
      select: "",
      // 选项
      options: regionData,
      // 选中的值用数组存储
      areaArr: [],
      // 筛选的地区
      receiptAddress: "",
      // tag的类型，根据status变化
      type: "",
      // 是否加载动画
      loading: true,
      // 新增订单
      newOrders: [],
      // 当前页
      current: 1,
      // 每页个数
      pageSize: 10,
      // 可选择每页个数
      pageSizes: [10, 20, 30, 50],
      // 总数
      total: 10,
      order1:{},
      adminList: [],
      currentPage: 1
    };
  },
  watch: {
    current: "getNewOrderList",
    pageSize: "getNewOrderList",
    selectedService(newVal, oldVal) {
      console.log(`从${oldVal}变更为${newVal}`);
      this.getEmployee(newVal);
    }
  },
  created() {
    this.getNewOrderList();
    this.getService();
  },
  methods: {
    getEmployee(category){
      this.$axios
          .get(
              `/admin/slist/${this.current}/${this.pageSize}`,
              {
                params: {
                  signature: category // 请求参数
                }
              }
          )
          .then((res) => {
            // this.adminList = res.data.data.data.records;
            this.adminList = [];
            res.data.data.data.records.forEach(item=>{
              this.adminList.push({id: item.id,realName: item.realName})
            })
            this.total = res.data.data.data.total;
            this.adminListIsLoading = false;
            console.log("获取家政人员列表",this.adminList)
          });
    },
    getService(){
      this.$axios
          .get(
              "/sortList/" +
              this.currentPage +
              "/" +
              this.pageSize +
              "/"+''
          )
          .then((res) => {
            this.services = [];
            console.log(res,this.adminList);
            res.data.data.sortData.records.forEach(item=>{
              this.services.push({label: item.category, value: item.sortId});
            });
            console.log(this.adminList);
          });
    },
    splitArr(str){
      let arr = str.split(";");
      for(let i=0; i<arr.length; i++){
        let temp = arr[i].split(",");
        this.polylineArr.push({
          "lng": parseFloat(temp[0]),
          "lat": parseFloat(temp[1])
        });
      }
    },
    shengchengluj(){
      this.$axios.get('https://restapi.amap.com/v3/direction/driving?origin='+this.startCoordinate.lon+','+this.startCoordinate.lat+'&destination='+this.endCoordinate.lon+','+this.endCoordinate.lat+'' +
          '&key=c0855ec0cf8fa39893bd7d8898993f70'
      ).then((res) => {
        let stepsArr = res.data.route.paths[0].steps;
        stepsArr.forEach((item,index)=>{
          this.instructionArr.push(item.instruction)
          this.splitArr(item.polyline)
        })
        this.ulShow = true;
      });
    },
    initMap() {
      AMapLoader.reset()
      AMapLoader.load({
        key: '23405e95488ea44adb93a5fe065f7886',
        version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Marker'], // 需要使用的的插件列表
        AMapUI: {
          version: '1.1',
          plugins: []
        }
      }).then((AMap) => {
        this.map = new AMap.Map('guide-map', {
          viewMode: "2D",
          zoom: 13,
          resizeEnable: true,
          willreadoften: true,
//                      center:this.mapCenter
          center:[117.0,36.4]
        });
        this.map.on('click', this.clickMapHandler)
      }).catch(e => {
        console.log(e);
      });
    },
    clickMapHandler(e) {
//          console.log(e)
      //选择起点
      if (this.isStart) {
        if (this.startMarker !== null) {
          this.map.remove(this.startMarker)
        }
        this.startCoordinate.lon = e.lnglat.getLng()
        this.startCoordinate.lat = e.lnglat.getLat()
        this.startCoordinateDescription = '经度：' + this.startCoordinate.lon + ',     纬度：' + this.startCoordinate.lat
//              console.log("startCoordinateDescription===========",this.startCoordinateDescription)
        //标点
        this.startMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat
              .getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: '起点',
          label: {
            content: '起点'
          }
        })
        // 将创建的点标记添加到已有的地图实例
        this.map.add(this.startMarker)
      }
      //选择终点
      else {
        if (this.endMarker !== null) {
          this.map.remove(this.endMarker)
        }
        this.endCoordinate.lon = e.lnglat.getLng()
        this.endCoordinate.lat = e.lnglat.getLat()
        this.endCoordinateDescription = '经度：' + this.endCoordinate.lon + ',     纬度：' + this.endCoordinate.lat
        this.endMarker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat
              .getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: '终点',
          label: {
            content: '终点'
          }
        })
//              console.log("endCoordinateDescription===========",this.endCoordinateDescription)

        this.map.add(this.endMarker)
      }
    },
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      //清除marker
      if (this.searchMarker) {
        this.map.remove(this.searchMarker)
      }
      //设置marker
      this.searchMarker = new AMap.Marker({
        map: this.map,
        position: [val.location.lng, val.location.lat],
      });
      this.keywords = val.name
      //定位
      this.map.setCenter([val.location.lng, val.location.lat])
    },
    sendDrug(order) {
      this.order1 = order
      this.dialog = true
      this.form = {
        emp: '',//服务人员
        empPhone: '',//服务人员电话
        empCompany: '',//家政公司
        instruction:'',//路径规划提示
        polyline:'',//路径规划坐标
      }
      this.ulShow=false,
          this.instructionArr=[]//路径规划中文介绍
      this.polylineArr=[]//路径规划线路经纬度
    },
    sendOrder(){
      let formData = new FormData();
      formData.append("orderId", this.order1.orderId);
      formData.append("emp", this.form.emp);
      formData.append("empPhone", this.form.empPhone);
      formData.append("empCompany", this.form.empCompany);
      formData.append("instruction", this.instructionArr);
      formData.append("polyline", JSON.stringify(this.polylineArr));
      let userInfo = this.$store.getters.getUser;
      formData.append("username",userInfo.username)

      this.$axios.post("/admin/order/send", formData).then((res) => {
//              console.log(res);
        if (res.data.status) {
          this.getNewOrderList();
          this.loading = false;
          this.dialog = false;
          this.$message({
            type: "success",
            message: "派单成功!",
          });
          // 记录日志
          this.$axios.get("/admin/info/" + this.$store.getters.getUser.id, {
            headers: {
              Authorization: localStorage.getItem("token")
            }
          }).then((res) => {
            let user = res.data.data.data;
            let formData = new FormData();
            formData.append(
                "auth",
                user.auth == 1 ? "超级管理员" : "管理员"
            );
            formData.append("admin", user.realName);
            let doWhat =
                "将订单编号 " +
                order.orderId +
                " 的状态'未派单'修改为'已派单'";
            formData.append("doWhat", doWhat);
            this.$axios.post("/log/add", formData);
          });
        }
      });



    },
    handleClose(done) {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
      // if (this.loading) {
      //   return;
      // }
      // this.$confirm('确定要提交表单吗？')
      //     .then(_ => {
      //       this.loading = true;
      //       this.timer = setTimeout(() => {
      //         done();
      //         // 动画关闭需要一定的时间
      //         setTimeout(() => {
      //           this.loading = false;
      //         }, 400);
      //       }, 2000);
      //     })
      //     .catch(_ => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },

    // 获取新增订单
    getNewOrderList() {
      // 未派单的status == 1
      const status = 1;
      if (this.flag == 0) {
        this.$axios
            .get(
                "/admin/order/" + this.current + "/" + this.pageSize + "/" + status
            )
            .then((res) => {
              console.log("最新订单==>", res);
              this.newOrders = res.data.data.responseBody.orderList;
              this.total = res.data.data.responseBody.total;
              this.loading = false;
            });
      } else if (this.flag == 1) {
        let formData = new FormData();
        formData.append("receiptAddress", this.receiptAddress);
        formData.append("current", this.current);
        formData.append("size", this.pageSize);
        formData.append("status", status);
        this.$axios.post("/admin/orderWith/address", formData).then((res) => {
          console.log("最新订单==>", res);
          this.newOrders = res.data.data.responseBody.orderList;
          this.total = res.data.data.responseBody.total;
          this.loading = false;
        });
      } else if (this.flag == 2) {
        let formData = new FormData();
        formData.append("type", this.select);
        formData.append("content", this.input.trim());
        formData.append("current", this.current);
        formData.append("size", this.pageSize);
        formData.append("status", status);
        this.$axios.post("/admin/orderWith/search", formData).then((res) => {
          console.log("最新订单==>", res);
          this.newOrders = res.data.data.responseBody.orderList;
          this.total = res.data.data.responseBody.total;
          this.loading = false;
        });
      }
    },
    // 查看全部
    lookAll() {
      this.flag = 0;
      this.getNewOrderList();
    },
    // 根据地址筛选
    selectWithAddress() {
      if (this.receiptAddress != "") {
        this.flag = 1;
        this.getNewOrderList();
      }
    },
    // 搜索
    searchWithContent() {
      if (this.select != "" && this.input != "") {
        this.flag = 2;
        this.getNewOrderList();
      }
    },
    // 区域地址改变
    chooseArea() {
      // 展示的你选择的值 是一个areaCode
      console.log("chooseArea ==> ", this.areaArr);
      // 把areaCode转换成地名并拼接起来
      let str = "";
      for (let i = 0; i < this.areaArr.length; i++) {
        str += CodeToText[this.areaArr[i]] + "/";
      }
      console.log(str.substring(0, str.length - 1));
      this.receiptAddress = str.substring(0, str.length - 1);
    },
    // 去除地址的 / ，拼接
    showAddress(address) {
      if (address != "" && address != null) {
        let arr = address.split("/");
        let str = "";
        for (const item of arr) {
          str += item;
        }
        return str;
      }
    },
    /* 展示对应状态 */
    showStatus(status) {
      switch (status) {
        case -1:
          this.type = "danger";
          return "被投诉";
        case 0:
          this.type = "warning";
          return "交易取消";
        case 1:
          this.type = "info";
          return "未派单";
        case 2:
          this.type = "";
          return "已派单";
        case 3:
          this.type = "success";
          return "完成服务";
        default:
          return "未知";
      }
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
    },
  },
};
</script>

<style scoped>
@import "./style/NewOrder.css";
</style>
